extends Node2D

const tile_size = 16

var direction : Vector2 = Vector2.DOWN
var coords : Vector2 = Vector2(1, 0)
var hunger : int = 30

@onready var animation = $AnimationPlayer

var tween

signal command_finished
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	animation.play("idle_down")

func move() -> void:
	tween = get_tree().create_tween()
	match direction:
		Vector2.DOWN:
			animation.play("run_down")
		Vector2.UP:
			animation.play("run_up")
		Vector2.LEFT:
			animation.play("run_left")
		Vector2.RIGHT:
			animation.play("run_right")
	tween.tween_property(self, "position", position + direction * tile_size, 1.5)
	coords += direction
	hunger -= 1
	await tween.finished
	command_finished.emit()

func die() -> void:
	if hunger == 0:
		match direction:
			Vector2.DOWN:
				animation.play("die_down")
			Vector2.UP:
				animation.play("die_up")
			Vector2.LEFT:
				animation.play("die_left")
			Vector2.RIGHT:
				animation.play("die_right")

func rotate_left() -> void:
	match direction:
		Vector2.DOWN:
			animation.play("rotate_down_left")
			direction = Vector2.RIGHT
		Vector2.UP:
			animation.play("rotate_up_left")
			direction = Vector2.LEFT
		Vector2.LEFT:
			animation.play("rotate_left_left")
			direction = Vector2.DOWN
		Vector2.RIGHT:
			animation.play("rotate_right_left")
			direction = Vector2.UP
	await animation.animation_finished
	command_finished.emit()

func rotate_right() -> void:
	match direction:
		Vector2.DOWN:
			animation.play("rotate_down_right")
			direction = Vector2.LEFT
		Vector2.UP:
			animation.play("rotate_up_right")
			direction = Vector2.RIGHT
		Vector2.LEFT:
			animation.play("rotate_left_right")
			direction = Vector2.UP
		Vector2.RIGHT:
			animation.play("rotate_right_right")
			direction = Vector2.DOWN
	await animation.animation_finished
	command_finished.emit()
